package com.abc.robot01.activity

import android.os.Bundle
import android.util.Log
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.abc.robot01.R

import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.compose.ui.window.Popup
import androidx.lifecycle.lifecycleScope
import com.abc.robot01.activity.SysMessageActivity.Companion.size
import com.abc.robot01.retrofit.RetrofitService
import com.abc.robot01.retrofit.bean.HouseType
import com.abc.robot01.retrofit.bean.Item8
import com.abc.robot01.vivemodel.HouseLayoutViewModel
import com.abc.robot01.vivemodel.Robot
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
import com.bumptech.glide.integration.compose.GlideImage
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

/**
 * 户型选择
 */
class HuXingXuanZheActivity : BaseActivity() {

    private val viewModel: HouseLayoutViewModel by viewModels()

    /**
     *  选择户型
     */
    @Composable
    fun TAB1() {
        // 获取键盘控制器
        val keyboardController = LocalSoftwareKeyboardController.current

        val expanded1 = remember { viewModel.expanded1 }
        val selected1 = remember { viewModel.selected10 }

        val expanded2 = remember { viewModel.expanded2 }
        val selected2 = remember {viewModel.selected20}

        val items: List<HouseType> by viewModel.houseTypeList.collectAsState()

        Row(verticalAlignment = Alignment.CenterVertically) {
            BasicText(
                modifier = Modifier.offset(y = 0.dp),
                text = "户型名称",
                style = TextStyle(
                    fontWeight = FontWeight.Normal,
                    fontSize = 26.mysp,
                    color = MYBLACK,
                ),
            )
            Spacer(modifier = Modifier.width(20.px))
            val name = remember { viewModel.name }
            CustomStyledTextField2(text = name,textColor = MYBLACK_Percent5)
            Spacer(modifier = Modifier.width(78.px))
            BasicText(
                modifier = Modifier.offset(y = 0.dp),
                text = "户型",
                style = TextStyle(
                    fontWeight = FontWeight.Normal,
                    fontSize = 26.mysp,
                    color = MYBLACK,
                ),
            )
            Spacer(modifier = Modifier.width(20.px))
            Column {
                CustomStyledTextField4(selected1,textColor = MYBLACK_Percent5) {
                    expanded1.value = expanded1.value.not()
                }
                if (expanded1.value) {
                    MyDropdownMenu(expanded1, selected1,
                        selectedCode = viewModel.selectedHouseType,
                        offsetY = 10.px,
                        items2=items.map { it.name to  it.code }
                        )
                }
            }
        }

        Spacer(modifier = Modifier.height(33.px))

        Row(verticalAlignment = Alignment.CenterVertically) {
            BasicText(
                modifier = Modifier.offset(y = 0.dp),
                text = "社区名称",
                style = TextStyle(
                    fontWeight = FontWeight.Normal,
                    fontSize = 26.mysp,
                    color = MYBLACK,
                ),
            )
            Spacer(modifier = Modifier.width(20.px))
            val shequ = remember { viewModel.shequ }
            CustomStyledTextField2(shequ,textColor = MYBLACK_Percent5,
                enabled = false
            )
            Spacer(modifier = Modifier.width(54.px))
            BasicText(
                modifier = Modifier.offset(y = 0.dp),
                text = "创建者",
                style = TextStyle(
                    fontWeight = FontWeight.Normal,
                    fontSize = 26.mysp,
                    color = MYBLACK,
                ),
            )

            Spacer(modifier = Modifier.width(20.px))
            Column {
                CustomStyledTextField4(selected2,textColor = MYBLACK_Percent5) {
                    expanded2.value = expanded2.value.not()
                }
                val items2: List<Pair<String,String>> by viewModel.designerList.collectAsState()
                if (expanded2.value) {
                    MyDropdownMenu(expanded2, selected2, selectedCode = viewModel.selectedDesigner,
                        offsetY = 90.px,
                        items2= items2
                    )
                }
            }

            Spacer(modifier = Modifier.width(30.px))
            MyButton01(
                text = "查询", size = DpSize(148.px, 50.px), textColor = Color.White,
                containerColor = MYBLUE, shape = RoundedCornerShape(25)
            ) {
                keyboardController?.hide()
                viewModel.loadData()
            }

            Spacer(modifier = Modifier.width(30.px))
            MyButton01(
                text = "重置",
                size = DpSize(148.px, 50.px),
                textColor = MYBLACK,
                containerColor = MYBLACK_Percent10,
                shape = RoundedCornerShape(25)
            ) {
                keyboardController?.hide()
                viewModel.reset()
//                viewModel.loadData();
            }
        }
        Spacer(modifier = Modifier.height(30.px))
        SimpleGrid()
    }

    @OptIn(ExperimentalGlideComposeApi::class)
    @Composable
    fun SimpleGrid(columns: Int = 7) {
        val items: List<Item8> by viewModel.questionList.collectAsState()
        if (items.size == 0) {
            Column(
                modifier = Modifier.fillMaxSize(),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                GlideImage(
                    model = R.drawable.empty,
                    contentDescription = "",
                )
                Spacer(modifier = Modifier.height(30.px))
                BasicText(
                    maxLines = 1,
                    overflow = TextOverflow.Clip,
                    text = "暂无数据",
                    style = TextStyle(
                        fontSize = 30.mysp,
                        color = MYBLACK,
                    )
                )
            }
            return
        }

        // Track the currently selected item index
        val selectedIndex = remember { viewModel.selectedIndex }
        LazyVerticalGrid(
            verticalArrangement = Arrangement.spacedBy(20.px), // 可以设置垂直间隔，例如16dp
            horizontalArrangement = Arrangement.spacedBy(20.px), // 水平间隔设置为 20px
            columns = GridCells.Fixed(columns), // 2 columns in the grid
            modifier = Modifier
                .fillMaxWidth()
                .height(592.px)
                .padding(start = 0.px, end = 0.px, top = 0.px)
        ) {
            itemsIndexed(items, key = { index, item  -> item.id + item.name }) { index,item ->
                Log.e(TAG,"thumbnail:"+item.thumbnail.toString())
                ImageTextCard(item,index,selectedIndex)
            }
        }
    }

    @OptIn(ExperimentalGlideComposeApi::class)
    @Composable
    fun ImageTextCard(item: Item8, index: Int, selectedIndex: MutableState<Int>) {
        // Background color changes based on the selected state
        val backgroundColor = MYBLACK_Percent5
        Box(
            modifier = Modifier
                .clickable(
                    interactionSource = remember { MutableInteractionSource() },
                    indication = null,
                    onClick = { // Removes ripple effect))
                        selectedIndex.value = index
                        viewModel.selected1.value = item.renderCount > 0
                        viewModel.selected2.value = true
                        viewModel.housePlansId = item.id
                        viewModel.thumbnail = item.thumbnail!!
                    })
                .background(color = backgroundColor, shape = RoundedCornerShape(14.px))
                .width(240.px)
                .height(327.px)
        ) {
//            Box(modifier = Modifier.fillMaxSize().background(backgroundColor)) {
//            }
            Column(
                modifier = Modifier
                    .fillMaxSize().background(backgroundColor)
                    .padding(0.px),
                horizontalAlignment = Alignment.Start
            ) {
                Card(
                    colors = androidx.compose.material3.CardDefaults.cardColors(
                        containerColor = MYBLACK_Percent10 // 设置背景色为红色
                    ),
                    shape = RoundedCornerShape(10.px),
                    modifier = Modifier
                        .background(Color.Transparent)
                        .width(240.px)
                        .height(240.px)
                ) {
                    GlideImage(
                        contentScale = ContentScale.Fit,
                        model = item.thumbnail,
                        contentDescription = "",
                        modifier = Modifier.fillMaxSize()
                    )
                }
                Spacer(modifier = Modifier.height(10.px))
                BasicText(
                    modifier = Modifier.offset(x=20.px),
                    maxLines = 1,
                    overflow = TextOverflow.Clip,
                    text = item.name ?: "无名称",
                    style = TextStyle(
                        fontSize = (24 / 3.5f).sp,
                        color = Color.Black,
                        lineHeight = (24 / 3.5f).sp
                    )
                )
                Spacer(modifier = Modifier.height(5.px))

                Row(modifier = Modifier
                    .fillMaxWidth()
                    .padding(
                        start = 20.px, end = 20.px
                    )
                ) {
                    BasicText(
                        maxLines = 1,
                        overflow = TextOverflow.Clip,
                        text = "" + item.houseType,
                        style = TextStyle(
                            fontSize = (20 / 3.5f).sp,
                            color = MYBLACK_Percent60,
                            lineHeight = (24 / 3.5f).sp
                        )
                    )
                    Spacer(modifier = Modifier.weight(14f))
                    BasicText(
                        maxLines = 1,
                        overflow = TextOverflow.Clip,
                        text = "" + item.innerArea + "㎡",
                        style = TextStyle(
                            fontSize = (20 / 3.5f).sp,
                            color = MYBLACK_Percent60,
                            lineHeight = (24 / 3.5f).sp
                        )
                    )
                }
            }
            Image(
                modifier=Modifier.offset(x=189.px,y=40.px),
                painter = painterResource(id = if(selectedIndex.value == index) R.drawable.s13 else  R.drawable.s12), // 替换为你的图片资源ID
                contentDescription = null,
                contentScale = ContentScale.Crop, // 使图片填充整个背景
            )
            if(selectedIndex.value == index) {
                Box(modifier = Modifier.fillMaxSize().background( shape = RoundedCornerShape(14.px), color = MYBLUE.copy(alpha = 0.4f))) {
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        viewModel.reset()
    }

    @Composable
    fun BoxScope.TopTabs(){
        val showLeft = remember { viewModel.showLeft }
        val showRight = remember { viewModel.showRight }
        val showCenter = remember { viewModel.showCenter }

        if (showLeft.value) {
            Image(
                modifier = Modifier.align(Alignment.TopStart),
                painter = painterResource(id = R.drawable.tab_left), // 替换为你的图片资源ID
                contentDescription = null,
                contentScale = ContentScale.Crop, // 使图片填充整个背景
            )
        }

        if (showCenter.value) {
            Image(
                modifier = Modifier.align(Alignment.Center),
                painter = painterResource(id = R.drawable.tab_center), // 替换为你的图片资源ID
                contentDescription = null,
                contentScale = ContentScale.Crop, // 使图片填充整个背景
            )
        }

        if (showRight.value) {
            Image(
                modifier = Modifier.align(Alignment.BottomEnd),
                painter = painterResource(id = R.drawable.tab_right), // 替换为你的图片资源ID
                contentDescription = null,
                contentScale = ContentScale.Crop, // 使图片填充整个背景
            )
        }

        Row(
            modifier = Modifier
                .fillMaxSize()
                .padding(start = 50.px)
                .offset(0.dp, 0.dp),
            horizontalArrangement = Arrangement.spacedBy(
                55.px
            ),
            verticalAlignment = Alignment.CenterVertically
        ) {
            BasicText(
                text = "选择户型",
                style = TextStyle(
                    fontWeight = FontWeight.Bold,
                    fontSize = size,
                    color = if (showLeft.value) MYBLACK else MYBLACK_Percent60,
                ),
                modifier = Modifier
                    .clickable(
                        indication = null,  // Removes the ripple effect
                        interactionSource = remember { MutableInteractionSource() }  // Keeps track of interactions
                    ) {
                        showLeft.value = true;
                        showCenter.value = false
                        showRight.value = false;
                    }
            )
            BasicText(
                text = "导入户型",
                style = TextStyle(
                    fontWeight = FontWeight.Bold,
                    fontSize = size,
                    color = if (showCenter.value) MYBLACK else MYBLACK_Percent60,
                ),
                modifier = Modifier
                    .clickable(
                        indication = null,  // Removes the ripple effect
                        interactionSource = remember { MutableInteractionSource() }) {
                        showLeft.value = false;
                        showCenter.value = true
                        showRight.value = false;

                    }
            )
            BasicText(
                text = "绘制户型",
                style = TextStyle(
                    fontWeight = FontWeight.Bold,
                    fontSize = size,
                    color = if (showRight.value) MYBLACK else MYBLACK_Percent60,
                ),
                modifier = Modifier
                    .clickable(
                        indication = null,  // Removes the ripple effect
                        interactionSource = remember { MutableInteractionSource() }) {
                        showLeft.value = false;
                        showCenter.value = false
                        showRight.value = true;
                    }
            )
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val designPackageId = intent.getStringExtra("designPackageId");
        viewModel.designPackageId.value = designPackageId!!;
        viewModel.loadData()
        setContent {
            val showLeft = remember { viewModel.showLeft }
            val selected1 by remember  { viewModel.selected1}
            val selected2 by remember  { viewModel.selected2}

            val selectedIndex by remember  { viewModel.selectedIndex}

            MaterialTheme {
                Box {
                    Image(painter = painterResource(id = R.drawable.z1), contentDescription = "")
                    Column(modifier = Modifier.padding(start = 30.px, end = 30.px, top = 30.px)) {
                        BackButton {
                        }
                        Spacer(modifier = Modifier.height(30.px))
                        Box(
                            modifier = Modifier
                                .size(570.px, 90.px)
                                .background(
                                    Color(0x00bac3db),
                                ),
                        ) {
                            // 背景图片
                            Box(
                                modifier = Modifier
                                    .size(570.px, 90.px)
                                    .background(
                                        Color.White.copy(alpha = 0.4f),
                                        shape = RoundedCornerShape(40.px, 40.px, 0.px, 0.px)
                                    ),
                            )
                            TopTabs()
                        }
                        SystemFragmentBackground3 {
                            Column(modifier = Modifier.padding(start = 30.px, end = 30.px)) {
                                Spacer(modifier = Modifier.height(30.px))
                                if (showLeft.value) {
                                    TAB1()
                                }
                            }
                        }
                    }
                    BottomBar(
                        //张伟要求去掉取消
                        show = false,
                        selected1 = selected1,
                        selected2 = selected2,
                        onClick3 =  { viewModel.reset()},
                        onClick = {
                            viewModel.loading.value=true
                            lifecycleScope.launch {
                                if(viewModel.housePlansId.isEmpty())
                                   return@launch
                                val res = RetrofitService.instance.saveReadingTask(
                                    accessToken = Robot.accessToken,
                                    userId = Robot.userId,
                                    companyId = Robot.companyId,
                                    housePlansId = viewModel.housePlansId,
                                    designPackageId = viewModel.designPackageId.value,
                                    fileUrl = viewModel.thumbnail!!,
                                )
                                Log.e(TAG, "户型识别结果:" + res.code)
                                val code = res.code
                                if (code == 200
                                ) {
                                    Log.e(TAG, "户型识别结果:" + res.data)
                                    lifecycleScope.launch {
                                        while (true) {
                                            delay(1000)
                                            val a = RetrofitService.instance
                                                .getTaskStatus(
                                                    accessToken = Robot.accessToken,
                                                    userId = Robot.userId,
                                                    companyId = Robot.companyId,
                                                    taskId = res.data
                                                )
                                                .string()

                                            Log.e(TAG, "户型识别结果 轮询获取图片识别数据:" + a)

                                            val status = JSONObject(a)
                                                .getJSONObject("data")
                                                .getString("status")
                                            if (status == "2") {
                                                Log.e(TAG, "户型识别 成功:")
                                                val housePlansId =
                                                    JSONObject(a)
                                                        .getJSONObject("data")
                                                        .getString("housePlansId")

                                                startActivity<HuXingTiaoZheng>() {
                                                    putExtra("housePlansId", "" + housePlansId)
                                                    putExtra("designPackageId", "" + designPackageId)
                                                }
                                                viewModel.loading.value=false
                                                break
                                            }
                                        }
                                    }
                                }
                            }


                        }, onClick2 = {
                            startActivity<HuXingShuJuActivity>() {
                                putExtra("housePlansId", viewModel.housePlansId)
                                putExtra("designPackageId", viewModel.designPackageId.value)
                            }
                        })
                    val loading = remember { viewModel.loading }
                    LoadingDialog(loading)
                }
            }
        }
    }


    companion object {
        val TAG = "HuXingXuanZheActivity"
    }
}

@Composable
fun LoadingDialog(loading:MutableState<Boolean>) {
    if (loading.value) {
        Dialog(
            onDismissRequest = {}, // 禁用点击外部关闭对话框
            properties = DialogProperties(
                dismissOnBackPress = false, // 禁用返回按钮
                dismissOnClickOutside = false // 禁用点击外部关闭对话框
            )
        ) {
            Box(
                contentAlignment = Alignment.Center,
                modifier = Modifier
                    .size(200.dp) // 设置对话框的大小
                    .background(Color.Transparent) // 设置背景颜色
            ) {
                CircularProgressIndicator(
                    color = Color.Blue, // 进度指示器的颜色
                    strokeWidth = 4.dp
                )
            }
        }
    }
}

@Composable
fun MyDropdownMenu(
    expanded: MutableState<Boolean>,
    selectedName: MutableState<String>,
    selectedCode: MutableState<String>,
    width: Dp = 374.px,
    height: Dp = 800.px,
    items2: List<Pair<String,String>>,
    offsetX: Dp = 0.px,
    offsetY: Dp = 0.px
) {
    Column(modifier = Modifier.background(Color.Blue)) {
        Popup(
            alignment = Alignment.TopStart,
            offset = IntOffset(0 * 30, 0),
            onDismissRequest = { expanded.value = false }) {
            Card(modifier = Modifier
                .width(width).height(height)
                .offset(y = offsetY),
                shape = RoundedCornerShape(bottomStart=10.px, bottomEnd = 10.px),
                colors = CardDefaults.cardColors(containerColor = Color.White),
            ) {
                DrawScrollableView(modifier = Modifier.width(1000.px)
                    .fillMaxHeight()) {
                                        Column {
                    items2.forEach {
                        Box(
                            modifier = Modifier
//                                    .background(
//                                        color = Color.Transparent,
//                                        shape = RoundedCornerShape(5.px))
                                .fillMaxWidth()
                                .height(80.px), // 修改为 dp 或者其他单位
                            contentAlignment = Alignment.CenterStart // 垂直和水平居中
                        ) {
                            BasicText(
                                modifier = Modifier
                                    .clickable {
                                        expanded.value = false
                                        selectedName.value = it.first
                                        selectedCode.value = it.second

                                    }
                                    .fillMaxWidth()
                                    .height(80.px),
                                text = it.first,
                                style = TextStyle(
                                    fontWeight = FontWeight.Normal,
                                    textAlign = TextAlign.Center,
                                    fontSize = 26.mysp,
                                    color = Color.Black,
                                ),
                            )
                        }
                    }
                    }
                }
//                LazyColumn {
//                    items(items2, key = { it.first +it.second }) {
//                        Box(
//                            modifier = Modifier
////                                    .background(
////                                        color = Color.Transparent,
////                                        shape = RoundedCornerShape(5.px))
//                                .fillMaxWidth()
//                                .height(80.px), // 修改为 dp 或者其他单位
//                            contentAlignment = Alignment.CenterStart // 垂直和水平居中
//                        ) {
//                            BasicText(
//                                modifier = Modifier
//                                    .clickable {
//                                        expanded.value = false
//                                        selectedName.value = it.first
//                                        selectedCode.value = it.second
//
//                                    }
//                                    .fillMaxWidth()
//                                    .height(80.px),
//                                text = it.first,
//                                style = TextStyle(
//                                    fontWeight = FontWeight.Normal,
//                                    textAlign = TextAlign.Center,
//                                    fontSize = 26.mysp,
//                                    color = Color.Black,
//                                ),
//                            )
//                        }
//                    }
//                }
            }
        }
    }
}

@Composable
fun MyDropdownMenu2(
    expanded: MutableState<Boolean>,
    selectedName: MutableState<String>,
    selectedCode: MutableState<String>,
    width: Dp = 374.px,
    height: Dp = 800.px,
    items2: List<Pair<String,String>>,
    offsetX: Dp = 0.px,
    offsetY: Dp = 0.px,
    offsetX2: Int = 0,
    offsetY2: Int = 0,
    click: ((String) -> Unit) = {}
) {
    Column(modifier = Modifier.background(Color.Blue)) {
        Popup(
            alignment = Alignment.TopStart,
            offset = IntOffset(x=offsetX2, y=offsetY2),
            onDismissRequest = { expanded.value = false }) {
            Card(modifier = Modifier
                .width(width).wrapContentHeight()
                .offset(y = offsetY,x=offsetX),
                shape = RoundedCornerShape(bottomStart=10.px, bottomEnd = 10.px),
                colors = CardDefaults.cardColors(containerColor = Color.White),
            ) {
                DrawScrollableView(modifier = Modifier.width(1000.px)
                    .wrapContentHeight()) {
                    Column {
                        items2.forEach {
                            Box(
                                modifier = Modifier
//                                    .border(2.px, Color.Green)
//                                    .background(
//                                        color = Color.Transparent,
//                                        shape = RoundedCornerShape(5.px))
                                    .fillMaxWidth()
                                    .height(80.px), // 修改为 dp 或者其他单位
                                contentAlignment = Alignment.Center // 垂直和水平居中
                            ) {
                                BasicText(
                                    modifier = Modifier
                                        .clickable {
                                            expanded.value = false
                                            selectedName.value = it.first
                                            selectedCode.value = it.second
                                            click(it.first)
                                        }
                                        .fillMaxWidth(),
//                                        .height(80.px),
                                    text = it.first,
                                    style = TextStyle(
                                        fontWeight = FontWeight.Normal,
                                        textAlign = TextAlign.Center,
                                        fontSize = 26.mysp,
                                        color = Color.Black,
                                    ),
                                )
                            }
                        }
                    }
                }
            }
        }
    }
}


